import os
import time

import path
import tqdm
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks

from gxl_ai_utils.utils import utils_file

inference_pipeline_single = pipeline(
    task=Tasks.voice_activity_detection,
    model='damo/speech_fsmn_vad_zh-cn-16k-common-pytorch',
    model_revision=None,
    device='cpu',
    batch_size=100
)

inference_pipeline_scp = pipeline(
    task=Tasks.voice_activity_detection,
    model='damo/speech_fsmn_vad_zh-cn-16k-common-pytorch',
    model_revision=None,
    device='gpu',
    output_dir='./output/',
    batch_size=100,
)
print('---------->gxl:  ', inference_pipeline_scp.cfg)
inference_pipeline_scp.cfg.output_dir = './output/xlgeng'
print('---------->gxl:  ', inference_pipeline_scp.cfg)


def get_segments_for_audio(
        audio_in: str = "https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/test_audio/vad_example.wav"):
    """
    audio_in: url, file_path
    """
    # waveform, sample_rate = soundfile.read(audio_in)
    segments_result = inference_pipeline_single(
        audio_in=audio_in)
    return segments_result


def get_segments_for_scp_file(audio_in='./output/wav.scp'):
    inference_pipeline_scp(audio_in=audio_in)


def get_segements_for_scp_func2(wav_scp_file_path: str = './output/wav.scp',
                                target_json_file_path: str = './output/segments_task.scp'):
    dic_data = utils_file.load_dic_from_scp(wav_scp_file_path)
    utils_file.makedir_for_file(target_json_file_path)
    res_dic = {}
    num = 0
    print('开始得到得到wav.scp文件对应音频的切分段, 共有{}条数据'.format(len(dic_data)))
    for k, v in tqdm.tqdm(dic_data.items(), total=len(dic_data)):
        print(k)
        output = get_segments_for_audio(audio_in=v)
        res_dic[k] = output
        num += 1
        if num >= 10:
            break
    utils_file.write_dic_to_scp(res_dic, target_json_file_path)


if __name__ == '__main__':
    """"""
    print(f'总共需要处理{len(utils_file.load_dic_from_scp("./output/wav.scp"))}条数据')
    now = time.time()
    get_segments_for_scp_file()
    end = time.time()
    print(f'耗时{end - now}s')
